package org.csu.demo.nio_chat.clientwithWeb;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class ClientThread implements Runnable {

    private Selector selector;
    private Charset charset = Charset.forName("UTF-8");
    private List<String> messages;

    public ClientThread(Selector selector, List<String> messages) {
        this.selector = selector;
        this.messages = messages;
    }

    @Override
    public void run() {
        try {
            for (;;) {
                int readChannels = selector.select();
                if (readChannels == 0) {
                    continue;
                }

                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
                    iterator.remove();

                    if (selectionKey.isReadable()) {
                        try {
                            readOperator(selectionKey);
                        } catch (IOException e) {
                            // 处理服务器异常关闭连接的情况
                            System.out.println("服务器连接关闭: " + ((SocketChannel) selectionKey.channel()).getRemoteAddress());
                            selectionKey.cancel();
                            try {
                                selectionKey.channel().close();
                            } catch (IOException ex) {
                                ex.printStackTrace();
                            }
                            return;
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void readOperator(SelectionKey selectionKey) throws IOException {
        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        int readLength = socketChannel.read(byteBuffer);
        String message = "";
        if (readLength > 0) {
            byteBuffer.flip();
            message += charset.decode(byteBuffer);
        }
        socketChannel.register(selector, SelectionKey.OP_READ);
        if (message.length() > 0) {
            // 检查消息是否已存在于列表中，不存在则添加
            if (!messages.contains(message)) {
                messages.add(message);
            }
        }
    }
}